package org.niu.tree;

import java.util.LinkedList;
import java.util.Queue;

public class PathSum {
    int ans = 0;
    public int pathSum(TreeNode root, int targetSum) {
        Queue<TreeNode> q = new LinkedList<>();
        int ans = 0;
        q.add(root);
        while (!q.isEmpty()){
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = q.poll();
                dfs(poll,targetSum,0);

                if(poll.left != null) q.add(poll.left);
                if(poll.right != null) q.add(poll.right);
            }
        }
        return ans;
    }
    void dfs(TreeNode root, int targetSum,int curSum){
        if(root == null) return;
        if(curSum + root.val == targetSum){
            ans++;
        }
        dfs(root.left,targetSum,curSum+root.val);
        dfs(root.right,targetSum,curSum+root.val);
    }
}
